package com.baitai.framework.web.service;

import javax.annotation.Resource;

import com.baitai.common.core.domain.model.LoginBody;
import com.baitai.system.domain.SysUserZcyx;
import com.baitai.system.domain.SysVersion;
import com.baitai.system.domain.UserZhichengTemp;
import com.baitai.system.mapper.SysVersionMapper;
import com.baitai.system.service.ISysUserZcyxService;
import com.baitai.system.service.IUserZhichengTempService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.baitai.common.constant.CacheConstants;
import com.baitai.common.constant.Constants;
import com.baitai.common.constant.UserConstants;
import com.baitai.common.core.domain.entity.SysUser;
import com.baitai.common.core.domain.model.LoginUser;
import com.baitai.common.core.redis.RedisCache;
import com.baitai.common.exception.ServiceException;
import com.baitai.common.exception.user.BlackListException;
import com.baitai.common.exception.user.CaptchaException;
import com.baitai.common.exception.user.CaptchaExpireException;
import com.baitai.common.exception.user.UserNotExistsException;
import com.baitai.common.exception.user.UserPasswordNotMatchException;
import com.baitai.common.utils.DateUtils;
import com.baitai.common.utils.MessageUtils;
import com.baitai.common.utils.StringUtils;
import com.baitai.common.utils.ip.IpUtils;
import com.baitai.framework.manager.AsyncManager;
import com.baitai.framework.manager.factory.AsyncFactory;
import com.baitai.framework.security.context.AuthenticationContextHolder;
import com.baitai.system.service.ISysConfigService;
import com.baitai.system.service.ISysUserService;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
public class SysLoginService {
    private static final Logger log = LoggerFactory.getLogger(SysLoginService.class);
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysUserZcyxService userZcyxService;

    @Autowired
    private IUserZhichengTempService userZhichengTempService;

    @Autowired
    private ISysConfigService configService;
    @Autowired
    private SysVersionMapper versionMapper;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
        // 验证码校验
        validateCaptcha(username, code, uuid);
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match"), ""));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage(), ""));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"), ""));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled) {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            if (captcha == null) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"), ""));
                throw new CaptchaExpireException();
            }
            redisCache.deleteObject(verifyKey);
            if (!code.equalsIgnoreCase(captcha)) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error"), ""));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 登录前置校验
     *
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null"), ""));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match"), ""));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match"), ""));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked"), ""));
            throw new BlackListException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }

    public Map<String, Object> appLogin(LoginBody loginBody) {
        Map<String, Object> result = new HashMap<>();
        String username = loginBody.getUsername();
        String password = loginBody.getPassword();
        String currVersion = loginBody.getCurrVersion();
        String packageName = loginBody.getPackageName();
        String phoneSha1 = loginBody.getPhoneSha1();

        if (currVersion == null) {
            return null;
        } else if (StringUtils.isNotEmpty(currVersion) && Integer.parseInt(currVersion) <= 5) {
            return null;
        }

        // 登录前置校验
        loginPreCheck(username, loginBody.getPassword());
        // 用户验证
        Authentication authentication = null;
        try {

            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match"), ""));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage(), ""));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }

        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        SysUser sysUser = userService.selectUserById(loginUser.getUserId());
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"), sysUser.getIsPrivate()));
        recordLoginInfo(loginUser.getUserId());
        String currUserVersion = sysUser.getAppVersion();
        String userPackageName = sysUser.getPackageName();
        String userPhoneSha1 = sysUser.getPhoneSha1();
        String currentApkversion = sysUser.getCurrentApkversion();


        if (StringUtils.isNotEmpty(currVersion)) {
            if (StringUtils.isNotEmpty(currUserVersion)) {
                if (!currVersion.equals(sysUser.getAppVersion()) && Integer.parseInt(currVersion) > Integer.parseInt(currUserVersion)) {
                    userService.updateUserAppVersion(loginUser.getUserId(), currVersion);
                    currUserVersion = currVersion;
                }
            } else {
                userService.updateUserAppVersion(loginUser.getUserId(), currVersion);
                currUserVersion = currVersion;
            }
            //记录当前登录的APP版本
            if (StringUtils.isNotEmpty(currentApkversion)) {
                if (!currVersion.equals(currentApkversion)) {
                    userService.updateUserCurrentApkversion(loginUser.getUserId(), currVersion);
                }
            } else {
                userService.updateUserCurrentApkversion(loginUser.getUserId(), currVersion);
            }
        }
        boolean isZCYX = false;
        //记录登录包名
        if (StringUtils.isNotEmpty(packageName)) {
            if (StringUtils.isNotEmpty(userPackageName)) {
                if (!packageName.equals(sysUser.getPackageName())) {
                    userService.updateUserPackageName(loginUser.getUserId(), packageName);
                    userPackageName = packageName;
                }
            } else {
                userService.updateUserPackageName(loginUser.getUserId(), packageName);
                userPackageName = packageName;
            }
            if (packageName.equals("com.chengyi.integral")) {
                isZCYX = true;

            }
        }
        //记录登录APP的sha1值
        if (StringUtils.isNotEmpty(phoneSha1)) {
            if (StringUtils.isNotEmpty(userPhoneSha1)) {
                if (!phoneSha1.equals(sysUser.getPhoneSha1())) {
                    userService.updateUserPhoneSha1(loginUser.getUserId(), phoneSha1);
                }
            } else {
                userService.updateUserPhoneSha1(loginUser.getUserId(), phoneSha1);
            }
        }
        //获取父级相关信息
        if (StringUtils.isNotEmpty(sysUser.getAncestor())) {
            String ossUrl = "";
            String version = "";
            String isForce = "1";
            String placementIdOne = "";
            String placementIdTwo = "";
            String placementIdThree = "";
            String tobid_splash = "";
            String tobid_inner = "";
            String tobid_reward = "";
            String packageVersion = "";
            String packageTabs = "";
            String placementTwoCount = "";
            String[] userId = sysUser.getAncestor().split(",");
            //1,107,108
            SysUser manager;
            if (userId.length > 0) {
                if ("1".equals(userId[0]) && userId.length == 1) {
                    manager = sysUser;
                } else if ("1".equals(userId[0]) && userId.length > 1) {
                    manager = userService.selectUserById(Long.parseLong(userId[1]));
                } else {
                    manager = userService.selectUserById(Long.parseLong(userId[0]));
                }
                ossUrl = manager.getOssUrl();
                version = manager.getAppVersion();
                if (StringUtils.isNotEmpty(manager.getIsForce())) {
                    isForce = manager.getIsForce();
                }
                placementIdOne = manager.getPlacementIdOne();
                placementIdTwo = manager.getPlacementIdTwo();
                placementIdThree = manager.getPlacementIdThree();

                tobid_splash = manager.getTobidSplash();
                tobid_inner = manager.getTobidInner();
                tobid_reward = manager.getTobidReward();

                packageVersion = manager.getPackageVersion();
                packageTabs = manager.getPackageTabs();
                placementTwoCount = manager.getPlacementTwoCount();
            }
            if (StringUtils.isNotEmpty(sysUser.getOssUrl())) {
                ossUrl = sysUser.getOssUrl();
            }
            if (StringUtils.isNotEmpty(sysUser.getPackageTabs())) {
                packageTabs = sysUser.getPackageTabs();
            }
            if (StringUtils.isNotEmpty(sysUser.getPlacementTwoCount())) {
                placementTwoCount = sysUser.getPlacementTwoCount();
            }


            if (isZCYX) {
                SysUser itemManager = userService.selectUserById(Long.parseLong("109455"));
                placementIdOne = itemManager.getPlacementIdOne();
                placementIdTwo = itemManager.getPlacementIdTwo();
                placementIdThree = itemManager.getPlacementIdThree();

                tobid_splash = itemManager.getTobidSplash();
                tobid_inner = itemManager.getTobidInner();
                tobid_reward = itemManager.getTobidReward();
                if (currentApkversion.equals(itemManager.getAppVersion())) {
                    SysUserZcyx sysUserZcyx = userZcyxService.selectSysUserZcyxByUserId(sysUser.getUserId());
                    if (sysUserZcyx == null) {
                        sysUserZcyx = new SysUserZcyx();
                        sysUserZcyx.setUserId(sysUser.getUserId());
                        sysUserZcyx.setAncestor("1,109455,109458");
                        sysUserZcyx.setParentId(Long.parseLong("109458"));
                        sysUserZcyx.setSourceAncestor(sysUser.getAncestor());
                        sysUserZcyx.setSourceParentid(Long.parseLong(sysUser.getParentId()));
                        sysUserZcyx.setIsupload(0);
                        sysUserZcyx.setNotes("");
                        userZcyxService.insertSysUserZcyx(sysUserZcyx);
                    }
                }
            }
//                String zcyxVersion = redisCache.getCacheObject("zcyx_version");
//                if (zcyxVersion.equals(currentApkversion)) {
//                }
            result.put("placementIdOne", placementIdOne);
            result.put("placementIdTwo", placementIdTwo);
            result.put("placementIdThree", placementIdThree);

            result.put("tobidSplash", tobid_splash);
            result.put("tobibInner", tobid_inner);
            result.put("tobidReward", tobid_reward);

            result.put("packageVersion", packageVersion);
            result.put("packageTabs", packageTabs);
            result.put("placementTwoCount", placementTwoCount);
            result.put("isPrivate", sysUser.getIsPrivate());
            result.put("packageName", userPackageName);
            SysVersion sysVersion = new SysVersion();
            sysVersion.setAndroidUrl(ossUrl);
//            if (Integer.parseInt(version) >= Integer.parseInt(currUserVersion)) {
                sysVersion.setAndroidVersion(version);
//            } else {
//                sysVersion.setAndroidVersion(currUserVersion);
//            }
            sysVersion.setIsForce(isForce);
            result.put("version", sysVersion);
        }

        result.put("currUserVersion", currUserVersion);
        // 生成token
        result.put(Constants.TOKEN, tokenService.createToken(loginUser));
        return result;
    }

//    public static void main(String[] args) {
//        String andt = "1";
//        String []userid = andt.split(",");
//        log.debug(userid.length+"");
//    }
}
